<script lang="ts" setup>
import type { MenuItem } from '#/api/system/models';

import { ref } from 'vue';

import { useVbenDrawer } from '@vben/common-ui';

import { useVbenForm, z } from '#/adapter/form';
import {
  createMenuApi,
  getMenuListApi,
  updateMenuApi,
} from '#/api/system/menu';
import { $t } from '#/locales';
import { toTree } from '#/utils';

const emit = defineEmits<{
  success: [];
}>();

const formData = ref<MenuItem>();

const [Form, formApi] = useVbenForm({
  commonConfig: {
    componentProps: {
      class: 'w-full',
    },
  },
  schema: [
    {
      component: 'RadioGroup',
      componentProps: {
        buttonStyle: 'solid',
        optionType: 'button',
        options: [
          { label: '目录', value: 0 },
          { label: '菜单', value: 1 },
          { label: '按钮', value: 2 },
        ],
      },
      fieldName: 'type',
      label: '菜单类型',
      defaultValue: 1,
      // 占满二列空间 基线对齐
      formItemClass: 'col-span-2 items-baseline',
    },
    {
      component: 'ApiTreeSelect',
      componentProps: {
        allowClear: true,
        treeLine: true,
        labelField: 'title',
        valueField: 'id',
        childrenField: 'children',
        afterFetch: (data: any) => {
          return toTree(data);
        },
        api: getMenuListApi,
      },
      fieldName: 'parentId',
      label: '上级菜单',
      formItemClass: 'col-span-2 items-baseline',
    },
    {
      component: 'Input',
      fieldName: 'title',
      label: '菜单名称',
      rules: 'required',
    },
    {
      component: 'Input',
      dependencies: {
        if(values) {
          return values.type !== 2;
        },
        triggerFields: ['type'],
      },
      fieldName: 'name',
      label: '路由名称',
      rules: 'required',
    },
    {
      component: 'IconPicker',
      componentProps: {
        prefix: 'carbon',
      },
      dependencies: {
        if(values) {
          return values.type !== 2;
        },
        triggerFields: ['type'],
      },
      fieldName: 'icon',
      label: '图标',
      defaultValue: 'carbon:tag',
    },
    {
      component: 'Input',
      dependencies: {
        if(values) {
          return [0, 1].includes(values.type);
        },
        required(values) {
          return [0, 1].includes(values.type);
        },
        triggerFields: ['type'],
      },
      fieldName: 'path',
      label: '路由地址',
    },
    {
      component: 'Input',
      dependencies: {
        required(values) {
          return [1].includes(values.type);
        },
        triggerFields: ['type'],
      },
      fieldName: 'component',
      label: '组件路径',
    },
    {
      component: 'Input',
      dependencies: {
        if(values) {
          return values.type === 2;
        },
        required(values) {
          return [2].includes(values.type);
        },
        triggerFields: ['type'],
      },
      fieldName: 'permission',
      label: '权限标识',
    },
    {
      component: 'Input',
      dependencies: {
        if(values) {
          return values.type !== 2;
        },
        triggerFields: ['type'],
      },
      fieldName: 'link',
      label: '外链地址',
    },
    {
      component: 'Input',
      dependencies: {
        if(values) {
          return values.type !== 2;
        },
        triggerFields: ['type'],
      },
      fieldName: 'iframeSrc',
      label: '内嵌地址',
    },
    {
      component: 'InputNumber',
      componentProps: {
        min: 1,
        precision: 0,
      },
      fieldName: 'order',
      label: '排序',
      defaultValue: 100,
      rules: z.number().gte(0),
    },
    {
      component: 'RadioGroup',
      componentProps: {
        buttonStyle: 'solid',
        optionType: 'button',
        options: [
          { label: '缓存', value: true },
          { label: '不缓存', value: false },
        ],
      },
      dependencies: {
        if(values) {
          return values.type !== 2;
        },
        triggerFields: ['type'],
      },
      fieldName: 'keepAlive',
      label: '是否缓存',
      defaultValue: false,
    },
    {
      component: 'RadioGroup',
      componentProps: {
        buttonStyle: 'solid',
        optionType: 'button',
        options: [
          { label: '隐藏', value: true },
          { label: '不隐藏', value: false },
        ],
      },
      dependencies: {
        if(values) {
          return values.type !== 2;
        },
        triggerFields: ['type'],
      },
      fieldName: 'hideInMenu',
      label: '是否隐藏',
      defaultValue: false,
    },
    {
      component: 'Switch',
      componentProps: {
        checkedValue: 1,
        unCheckedValue: 0,
        checkedChildren: '启用',
        unCheckedChildren: '禁用',
        class: 'w-auto',
      },
      fieldName: 'status',
      label: '状态',
      defaultValue: 1,
    },
  ],
  showDefaultActions: false,
  // 一共二列
  wrapperClass: 'grid-cols-2',
});

const [Drawer, drawerApi] = useVbenDrawer({
  async onConfirm() {
    const { valid } = await formApi.validate();
    if (valid) {
      drawerApi.lock();
      const data = await formApi.getValues();
      try {
        await (formData.value?.id
          ? updateMenuApi(formData.value.id, data)
          : createMenuApi(data));
        drawerApi.close();
        emit('success');
      } finally {
        drawerApi.unlock();
      }
    }
  },
  onOpenChange(isOpen: boolean) {
    if (isOpen) {
      const data = drawerApi.getData<MenuItem>();
      if (data.parentId === 0) {
        data.parentId = undefined;
      }
      formData.value = data;
      formApi.setValues(data);
      drawerApi.setState({
        title: data?.id
          ? $t('ui.actionTitle.edit', ['菜单'])
          : $t('ui.actionTitle.create', ['菜单']),
      });
    }
  },
});
</script>

<template>
  <Drawer>
    <Form />
  </Drawer>
</template>
